package edu.rjxy.xjdx.emps.servlet;

import edu.rjxy.xjdx.emps.common.domain.User;
import edu.rjxy.xjdx.emps.service.UserService;
import edu.rjxy.xjdx.emps.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/changPassword")
public class ChangPasswordServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       boolean success = false;//操作是否成功
        String oldpassword = request.getParameter("oldpassword").trim();
        String newpassword = request.getParameter("newpassword").trim();
        String loginName = request.getParameter("loginName").trim();
        User userInDb= userService.findUserByLoginname(loginName);
        if(userInDb.getPassword().equals(oldpassword)){
            //修改密码
            userService.updatePasswordByLoginname(newpassword,loginName);
            success = true;
        }
        //根据结果处理
       String path = success?"/pages/login.jsp":"/pages/changPwd.jsp";
       if(success){
           request.setAttribute("msg","修改成功，请重新登录");
           request.getSession().invalidate();//如果成功,销毁session后再跳转到登录页面重新登录
       }else{
           request.setAttribute("msg","旧密码错误，请重新输入");
       }
       request.getRequestDispatcher(path).forward(request,response);
    }
}
